 
## This program is Copyright (C) 2011, Altuna Akalin (altuna.akalin@gmail.com)
## All rights reserved.

## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##     * Redistributions of source code must retain the above copyright
##       notice, this list of conditions and the following disclaimer.
##     * Neither the name of the <organization> nor the
##       names of its contributors may be used to endorse or promote products
##       derived from this software without specific prior written permission.

## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
## ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
## WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
## DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
## DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
## SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

## INSTALLS the eRRBS pipeline

use Getopt::Long;
use File::Spec;




# variables
my $pathtobismark  ="bismark_aa";
my $pathtofar      ="far";
my $pathtocutadapt ="cutadapt";
my $pathtobowtie   ="bowtie";
my $help;
GetOptions(
           'PATHTOBISMARK=s' =>\$pathtobismark,
	   'PATHTOFAR=s' =>\$pathtofar,
	   'PATHTOCUTADAPT=s' =>\$pathtocutadapt,
	   'PATHTOBOWTIE=s' =>\$pathtobowtie,
	   'help' =>\$help);


sub usage
{
print STDERR <<EndOfUsage;

Usage: perl $0 [options] 
see INSTALL.txt for details

options:
--PATHTOBISMARK  : full path to 'bismark'  executable ex: /home/user/bismark/bismark [ default: if in PATH, finds it in the unix PATH ]
--PATHTOFAR      : full path to 'FAR' adapter remover executable. ex: /home/user/far/buid/far [ default: if in PATH, finds it in the unix PATH ]
--PATHTOCUTADAPT : full path to 'cutadapt' adapter remover executable. ex: /home/local/bin/cutadapt [ default: if in PATH, finds it in the unix PATH ]
--PATHTOBOWTIE   : full path to 'bowtie' installation (A path to a folder not to the executable). ex: /home/opt/bowtie-0-12/ [ default: if in PATH, finds it in the unix PATH ]
EndOfUsage
exit;
}
if($help){usage();}



# check if scripts folder exists if not die
if(-e "scripts"){$foldertoscripts=File::Spec->rel2abs( "scripts");}
else{die "scripts folder couldn't be found in the current directory. Install failed, exiting....\n";}

# for the undefined arguments look in $ENV{PATH} and SCRIPTS folder
warn "\n!!!!!!    INSTALLING eRRBS PIPELINE    !!!!!!!\n";
warn "\nlooking for dependencies in your PATH variable and the provided locations\n\n";

# CHECK BISMARK
if($pathtobismark  eq "bismark_aa")
{
  my $path=searchPATH($pathtobismark,$foldertoscripts);
  if($path ne "bismark_aa"){$pathtobismark=$path;}else{ warn_nonexist("bismark_aa");}
}
else
{
  warn "checking if you gave the correct path for PATHTOBISMARK\n";
  if(-e $pathtobismark && -f $pathtobismark){warn "found bismark executable\n\n";}else{warn_nonexist_given("bismark_aa",$pathtobismark)}
}

# CHECK FAR
if($pathtofar  eq "far")
{
  my $path=searchPATH($pathtofar,$foldertoscripts);
  if($path ne "far"){$pathtofar=$path;}else{ warn_nonexist("far");}
}
else
{
  warn "checking if you gave the correct path for PATHTOFAR\n";
  if(-e $pathtofar && -f $pathtofar){warn "found far executable\n\n";}else{warn_nonexist_given("far",$pathtofar)}
}


# CHECK CUTADAPT
if($pathtocutadapt  eq "cutadapt")
{
  my $path=searchPATH($pathtocutadapt,$foldertoscripts);
  if($path ne "cutadapt"){$pathtocutadapt=$path;}else{ warn_nonexist("cutadapt");}
}
else
{
  warn "checking if you gave the correct path for PATHTOCUTADAPT\n";
  if(-e $pathtocutadapt && -f $pathtocutadapt){warn "found cutadapt executable\n\n";}else{warn_nonexist_given("cutadapt",$pathtocutadapt)}
}


# CHECK BOWTIE
if($pathtobowtie  eq "bowtie")
{
  my $path=searchPATH($pathtobowtie);
  if($path ne "bowtie"){
	$path=~ s/bowtie$//;
	$pathtobowtie=$path;
  }else{ warn_nonexist("bowtie");}
}
else
{
  warn "checking if you gave the correct path for PATHTOBOWTIE\n";
  if(-e $pathtobowtie){warn "found bowtie installation\n\n";}else{warn_nonexist_given("bowtie",$pathtobowtie)}
}



open(my $fh,">eRRBS");
print $fh <<program;
#!/bin/bash

## This program is Copyright (C) 2011, Altuna Akalin (altuna.akalin\@gmail.com)
## All rights reserved.

## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##     * Redistributions of source code must retain the above copyright
##       notice, this list of conditions and the following disclaimer.
##     * Neither the name of the <organization> nor the
##       names of its contributors may be used to endorse or promote products
##       derived from this software without specific prior written permission.

## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
## ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
## WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
## DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
## DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
## SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.




# DEPENDENCIES:
# far (adepter remover)
# bowtie (aligner)
# bismark_aa (aligner handler, my modifications should be there, you can not use bismark)
# methylationCall_fromBismark.v1.pl


# 0) get options and prepare usage instructions
usage="Usage: \$0 --prefix=[prefix] --indir=[indir] \\n
[prefix]_fastqPF.txt (this is a pass filter fastq file) must be present in [indir] (input directory)\\n
the results will be written to [indir] (input directory)\\n\\n
--indir is MANDATORY!!\\n
--prefix is MANDATORY!!\\n\\n
other options:\\n
--adapter    : adapter string, def:TGAGATCGGAAGAGCGGTTCAGCAGGAATGCCGAGACCGATCTCGTATGC\\n 
--genomePath : full path to bisulfate converted genome directory (convert genome using bismark tools), def: /scratchFast/ala2027/RRBS/genomes/hg18no_random\\n
--cutadapt   : if given, cutadapt program should be used instead of far from adapter trimming.\\n
--flowcellid : flowcell ids of the run,one string with no spaces (optional)\\n
--rundate    : rundates of the run,one string with no spaces (optional)\\n
--extrainfo  : any other info such as length,machine,one string with no spaces (optional) ex: 50bp_hiseq_RRBS_NBM\\n
--illumina   : illumina version. Defaults to 1.7, other options 1.8 and 1.9\\n
--verbose    : YES|NO, if YES all the intermediate files (trimmed fastq and alignment files) will be kept, if NO all the intermediate files will be deleted. default: YES\\n
"

ADAPTER=TGAGATCGGAAGAGCGGTTCAGCAGGAATGCCGAGACCGATCTCGTATGC
GENOMEPATH=/scratchFast/ala2027/RRBS/genomes/hg18no_random
FOLDERTOSCRIPTS=$foldertoscripts
PATHTOBISMARK=$pathtobismark
PATHTOFAR=$pathtofar
PATHTOCUTADAPT=$pathtocutadapt
PATHTOBOWTIE=$pathtobowtie 
ILLUMINA=1.7
CUTADAPT=NO
VERBOSE=YES

for i in \$*
do
	case \$i in
    	--prefix=*)
		PREFIX=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--indir=*)
		INDIR=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--flowcellid=*)
		FLOWCELLID=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--rundate=*)
		RUNDATE=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--extrainfo=*)
		EXTRAINFO=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--adapter=*)
		ADAPTER=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--genomePath=*)
		GENOMEPATH=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--cutadapt)
		CUTADAPT=YES
		;;
    	--illumina=*)
		ILLUMINA=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	--verbose=*)
		VERBOSE=`echo \$i | sed 's/[-a-zA-Z0-9]*=//'`
		;;
    	*)
                # unknown option
		;;
  	esac
done

#echo \$GENOMEPATH



if [ -z "\$PREFIX"  ] || [ -z "\$INDIR" ] ; then
    echo -e \$usage
    exit 1
fi

if [ ! -d "\$INDIR"  ] ; then
    echo -e "ERROR: There is no directory called '\$INDIR' \\n\\n"    
    echo -e \$usage
    exit 1
fi

if [ ! -e "\${INDIR}/\${PREFIX}_fastqPF.txt"  ] ; then
    echo -e "ERROR: There is no fastq file with proper name in '\$INDIR' directory"
    echo -e "The script expects existence of \${PREFIX}_fastqPF.txt\\n\\n"
    
    echo -e \$usage
    exit 1
fi

if [ ! -e "\${GENOMEPATH}/Bisulfite_Genome"  ] ; then
    echo -e "ERROR: There is no Bisulfite_Genome folder in the provided genome folder:  '\${GENOMEPATH}'"
    echo -e "Please give correct location for the converted genome folder\\n\\n"
    
    echo -e \$usage
    exit 1
fi


echo "flowcellid: \$FLOWCELLID" > \$INDIR/sequencing.info.txt
echo "rundate   : \$RUNDATE" >> \$INDIR/sequencing.info.txt
echo "extrainfo : \$EXTRAINFO" >> \$INDIR/sequencing.info.txt
echo "prefix    : \$PREFIX" >> \$INDIR/sequencing.info.txt
echo "indir     : \$INDIR" >> \$INDIR/sequencing.info.txt



# mkdir -p \$outdir || exit 1;

# 1) get fastq

# 2) trim adapters
cd \$INDIR

echo  "trim adapters..."

if [ \$CUTADAPT == "NO"  ]
then
    
    if [ -e \$PATHTOFAR  ]
    then
	echo  "trimming adapters with FAR..."
	\$PATHTOFAR --source \${PREFIX}_fastqPF.txt --target \${PREFIX}_fastqPF.txt.trimmed --format fastq --min-overlap 6 --adapter \$ADAPTER --min-readlength 21 --cut-off 2 --trim-end right_tail -th 4 -u 2 2>\${PREFIX}_trimming.log 
    else
       	echo  "FAR program could not be found in given location, make sure you installed FAR in given location [ \$PATHTOFAR ]"
	exit 1
    fi
else
    if [ -e \$PATHTOCUTADAPT  ]
    then
	echo  "trimming adapters with cutadapt..."
        ln -s \${PREFIX}_fastqPF.txt \${PREFIX}_fastqPF.fastq
        \$PATHTOCUTADAPT -e 0.2 -a \$ADAPTER -m 21 -O 6 \${PREFIX}_fastqPF.fastq > \${PREFIX}_fastqPF.txt.trimmed 2> cutadapt.log
    else
       	echo  "'cutadapt' program could not be found in given location, make sure you installed 'cutadapt' in given location [ \$PATHTOCUTADAPT ]"
	exit 1
    fi
fi






# 3)use bismark to align

echo  "bismark alignment started..."

cutoffIll=1.7 
compare_result=`echo "\$ILLUMINA > \$cutoffIll" | bc`

if [ \$compare_result -eq 1 ]
then

	perl \$PATHTOBISMARK --path_to_bowtie \$PATHTOBOWTIE  -l 50 -chunkmbs 512 -q --phred33-quals --directional --extendedse  \$GENOMEPATH \${PREFIX}_fastqPF.txt.trimmed
else
	perl \$PATHTOBISMARK --path_to_bowtie \$PATHTOBOWTIE  -l 50 -chunkmbs 512 -q --phred64-quals --directional --extendedse  \$GENOMEPATH \${PREFIX}_fastqPF.txt.trimmed
fi

if [ \$VERBOSE == "NO" ]
then
	rm \${PREFIX}_fastqPF.txt.trimmed
	gzip \${PREFIX}_fastqPF.txt &
fi

# 4) sort the file
echo  "sorting the alignment file..."

sort -t\$'\\t' -T . -k3,3 -k4,4n -k2,2 \${PREFIX}_fastqPF.txt.trimmed_bismark.txt > \${PREFIX}_AlignmentSortedForCall.txt

# gzip \${PREFIX}_fastqPF.txt.trimmed_bismark.txt &

# 5)call for methylation
echo  "call for methylations..."

perl \$FOLDERTOSCRIPTS/methylationCall_fromBismark.v2.pl --prefix=\${PREFIX} --illumina=\${ILLUMINA}  \${PREFIX}_AlignmentSortedForCall.txt


if [ \$VERBOSE == "NO" ]
then
	rm \${PREFIX}_fastqPF.txt.trimmed_bismark.txt
	rm \${PREFIX}_AlignmentSortedForCall.txt
fi

program
close $fh;

chmod(0755, "eRRBS");

warn "\n!!!!!!    eRRBS PIPELINE INSTALLED    !!!!!!!\nif there are WARNINGS during installation, pipeline may not work correctly\n\n";

##### FUNCTIONS ########################

sub searchPATH
{
  my ($name,$foldertoscripts)=@_;
  
  my @paths=File::Spec->path();
  push @paths,$foldertoscripts;

  foreach my $path (@paths)
  {
    if(-e $path."/".$name)
    {
      return ($path."/".$name);
    }
  }
  return $name;
}

sub warn_nonexist
{
  my ($name)=@_;
  warn "WARNING: $name can not be found in your PATH or in the scripts directory in the installation bundle\n";
  warn "MAKE sure the dependencies are installed correctly and they are in your PATH or give their full paths using the options, run $0 with --help to see the options \n\n";

}


sub warn_nonexist_given
{
  my ($name,$loc)=@_;
  warn "WARNING: $name can not be found in the location provided: $loc\n";
  warn "MAKE sure the dependencies are installed correctly in the specified locations or they are in your PATH\n\n";

}
